<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Session;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use App\AdminUsers;
use App\AdminRoles;
use App\AdminRoleActions;

class AdminController extends Controller
{
	
	/**
	 * 设置分页大小
	 */
	public $pageSize = null;
	
	
	public function __construct()
	{
		$this->pageSize	 = CS('admin_page_size')!=''?CS('admin_page_size'):20;
	}

	
	/**
	 * 管理员列表
	 */
	public function index(Request $req)
	{
		//权限验证
		if(!in_array('admin_list',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
		
		$role_id = isset($req->role_id)?trim($req->role_id):'';
		$title = trans('admin.admin_list');
		$roles = AdminRoles::all();
		
		if($role_id !== '')
		{
			$data = AdminUsers::leftJoin('admin_role','admin_users.role_id','=','admin_role.role_id')
			->where('admin_users.role_id',$role_id)
			->paginate($this -> pageSize);	
		}
		else
		{
			$data = AdminUsers::leftJoin('admin_role','admin_users.role_id','=','admin_role.role_id')
			->paginate($this -> pageSize);
		}
		
		return view('admin.admin.admin_list',['title'=>$title,
			'data' => $data,
			'roles' =>$roles,
			'role_id' => $role_id,
		]);
	}
	
	
	
	
	
	
	/**
	 * 管理员添加
	 */
	public function add(Request $req)
	{
		//权限验证
		if(!in_array('admin_add',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
		if($req -> isMethod('get'))
		{
			$title = trans('admin.admin_add');
			$roles = AdminRoles::all();
			return view('admin.admin.admin_add',['title'=> $title,
				'roles' =>$roles,
			]);
		}
		else if($req -> isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	        	'role_id'			=> 'required',
	            'name'				=> 'required|max:50|unique:admin_users,name',
	            'email' 			=> 'required|max:100|email|unique:admin_users,email',
	            'password'			=> 'required|max:60|confirmed|alpha_dash',
	            'password_confirmation'	=> 'required|max:60',
	        ];
			
	        $message = [
	            'role_id.required'	=> '请选择角色分组',
	            'name.required'	=> '用户名是必须的',
				'name.max' 		=> '用户名长度不能大于50',
				'name.unique'   => '用户名已存在',
	            'email.required'			=> '邮箱是必须的',
	            'email.max'					=> '邮箱长度不能大于100',
	            'email.email'				=> '邮箱格式不正确',
	            'email.unique'   	=> '邮箱已存在',
	            'password.required'			=> '密码是必须的',	
	            'password.confirmed'		=> '两次输入的密码不一致',
	            'password_confirmation.required'	=> '重复密码是必须的',	
	            'password.max'		=> '密码描述长度不能大于60',
	            'password.alpha_dash'			=> '密码只能由字母、数字、破折号（-）或下划线（_）组成',
	            'password_confirmation.max'		=> '密码描述长度不能大于60',
	            
	        ];
			
	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
			
			$salt = str_random(8);
			$pwd  = trim($req->password);
			AdminUsers::insert(['name' => trim($req->name),
				'role_id'	=> trim($req->role_id),
				'email'		=> trim($req->email),
				'salt'		=> $salt,
				'password'	=> $this->makePwd($salt,$pwd), 
				'create_at'	=> time(),
			]);
	
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'succ',
				'info' => trans('admin.add_succ'),
				'url' => url('admin/admin')
			]);
		}
	}


	/**
	 * 管理员修改
	 */
	public function update(Request $req,$id)
	{

		//权限验证
		if(!in_array('admin_edit',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}


		if($req -> isMethod('get'))
		{
			if(AdminUsers::where('id',$id)->count() < 1)
			{
				return redirect('admin/admin');
			}
			$title = trans('admin.admin_update');
			$roles = AdminRoles::all();
			$admin = AdminUsers::where('id',$id)->first();
			return view('admin.admin.admin_update',['title'=> $title,
				'roles' =>$roles,
				'admin' =>$admin,
			]);
		}
		else if($req -> isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	        	'role_id'			=> 'required',
	            'name'				=> 'required|max:50|unique:admin_users,name,'.$id.',id',
	            'email' 			=> 'required|max:100|email|unique:admin_users,email,'.$id.',id',
	            'password'			=> 'max:60|confirmed|alpha_dash',
	            'password_confirmation'	=> 'max:60',
	        ];
			
	        $message = [
	            'role_id.required'	=> '请选择角色分组',
	            'name.required'	=> '用户名是必须的',
				'name.max' 		=> '用户名长度不能大于50',
				'name.unique'   => '用户名已存在',
	            'email.required'			=> '邮箱是必须的',
	            'email.max'					=> '邮箱长度不能大于100',
	            'email.email'				=> '邮箱格式不正确',
	            'email.unique'   	=> '邮箱已存在',
	            'password.confirmed'		=> '两次输入的密码不一致',
	            'password.max'		=> '密码长度不能大于60',
	            'password.alpha_dash'			=> '密码只能由字母、数字、破折号（-）或下划线（_）组成',
	            'password_confirmation.max'		=> '密码长度不能大于60',
	            
	        ];
			
	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
			
			if($req->password !== '')
			{
				$salt = str_random(8);
				$pwd  = trim($req->password);
				AdminUsers::where('id',$id)
				->update(['name' => trim($req->name),
					'role_id'	=> trim($req->role_id),
					'email'		=> trim($req->email),
					'salt'		=> $salt,
					'password'	=> $this->makePwd($salt,$pwd),
					'update_at' => time(), 
				]);
			}
			else
			{
				AdminUsers::where('id',$id)
				->update(['name' => trim($req->name),
					'role_id'	=> trim($req->role_id),
					'email'		=> trim($req->email),
					'update_at' => time(),
				]);		
			}

			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'succ',
				'info' => trans('admin.update_succ'),
				'url' => url('admin/admin')
			]);
		}
	}	








	/**
	 * 删除管理员
	 */
	public function del(Request $req)
	{
		//权限验证
		if(!in_array('admin_del',session('access')))
		{
			return [
				'error' 	=> 1,
				'message'	=> false,
				'content'   => '没有该操作的权限!',
			];
		}
		
		if($req->id == session('admin.admin_id'))
		{
			return [
				'error' 	=> 1,
				'message'	=> false,
				'content'   => '不能删除自己 !',
			];
		}
		else
		{
			if(AdminUsers::where('id',$req->id)->count() > 0)
			{
				AdminUsers::where('id',$req->id)->delete();
				return [
					'error' 	=> 0,
					'message'	=> false,
					'content'   => '删除成功 !',
				];	
			}
		}
		
	}










	/**
	 * 	管理员登录
	 */
	public function login(Request $req)
	{
		if($req -> isMethod('get'))
		{
			$status = Session::has('admin.admin_id');
			if(!$status)
			{
				$title = trans('admin.login');
				return view('admin.admin.login',['title'=> $title]);		
			}
			else
			{
				return redirect('/admin');
			}
		}
		else if($req -> isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'name'				=> 'required|max:50',
	            'password'	        => 'required|max:60',
	            'captcha' 			=> 'required|captcha',
	        ];
			
	        $message = [
	            'name.required'	=> '用户名是必须的',
				'name.max' 		=> '用户名长度不能大于50',
	            'password.required'	=> '密码是必须的',
	            'password.max'		=> '密码长度不能大于60',
	            'captcha.required'	=> '验证码是必须的',
	            'captcha.captcha'	=> '验证码错误',
	        ];

	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
			
			if(AdminUsers::where('name',$req->name)->count() < 1)
			{
				return back() -> with('errors','用户名不存在!')->withInput($req->all());
			}
			else
			{
				$admin = AdminUsers::where('name',$req->name)->first();
				//登录成功
				if($this->cheackPwd($admin->salt,$admin->password,$req->password))
				{
					//设置管理员信息
					session::put('admin'  , $this->adminInfo($admin->id));
					//设置管理员权限
					session::put('access'  , $this->getAccess($admin->id));
					
					return redirect('/admin');	
				}
				else
				{
					return back() -> with('errors','密码错误!')->withInput($req->all());
				}
			}


		}
	}
	
	
	

	
	
	
	/**
	 *  登录验证
	 */
	public function cheakUser($name,$pwd)
	{
		if($name == '')
		{
			return ['error' => 1,
				'content' 	=> 'false',
				'message' 	=> '用户名不能为空 ！',
			];	
		}
		
		if($pwd == '')
		{
			return ['error' => 1,
				'content' 	=> 'false',
				'message' 	=> '密码不能为空！',
			];	
		}
		
		if(AdminUsers::where('name',$name)->count() < 1)
		{
			return ['error' => 1,
				'content' 	=> 'false',
				'message' 	=> '用户不存在 ！',
			];
		}
		else
		{
			$admin = AdminUsers::where('name',$name)->first();
			//登录成功
			if($this->cheackPwd($admin->salt,$admin->password,$pwd))
			{
				//设置管理员信息
				session::put('admin'  , $this->adminInfo($admin->id));
				//设置管理员权限
				session::put('access'  , $this->getAccess($admin->id));
				
				return ['error' => 0,
					'content' 	=> 'true',
					'message' 	=> '登录成功！',
				];				
			}
			else
			{
				return ['error' => 1,
					'content' 	=> 'false',
					'message' 	=> '密码错误！',
				];
			}
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * 设置管理员信息
	 */
	public function	adminInfo($id)
	{
		$info = [];
		$res  =  AdminUsers::leftJoin('admin_role','admin_users.role_id', '=', 'admin_role.role_id')
		->where('admin_users.id',$id)->first();
		$info['admin_name'] = $res->name;
		$info['admin_id']	= $res->id;
		$info['email']  	= $res->email;
		$info['last_ip']	= $res->last_ip;
		$info['last_login']	= date('Y-m-d H:i:s',$res->login_at);
		$info['now_login']	= date('Y-m-d H:i:s',time());
		$info['role_name']	= $res->role_name;
		$info['role_id']    = $res->role_id;
		//更新登录
		AdminUsers::where('id',$res->id)->update([
			'last_ip' 	=> getIP(),
			'login_at'	=> time(),
		]);
		return $info;
	}
	
	
	
	/**
	 * 获取管理员拥有的所有权限
	 */
	public function getAccess($id)
	{
		$res = AdminUsers::leftJoin('admin_role','admin_users.role_id','=','admin_role.role_id')
		->leftJoin('admin_role_actions','admin_role.role_id','=','admin_role_actions.role_id')
		->leftJoin('admin_actions','admin_role_actions.act_id','=','admin_actions.act_id')
		->select('admin_actions.node')
		->where('admin_users.id',$id)
		->get();
		return  array_flatten(json_decode(json_encode($res),true));
	}
	
	
	/**
	 * 生成密码
	 */
	public function makePwd($slat,$pwd)
	{
		return md5($slat.$pwd);
	}
	
	
	
	
	
	
	/**
	 * 检测密码
	 */
	public function cheackPwd($salt,$db_pwd,$password)
	{
		if(md5($salt.$password) == $db_pwd)
		{
			return true;
		}
		else
		{
			return false;
		}
	}	
	
	
	
	
	/**
	 * 注销账号
	 */
	public function logout()
	{
		session::forget('admin');
		session::forget('access');
		return redirect('admin/login');
	}
	
	
	
	
	
	
		

}
